package com.codefish.codefishseckill.config.interceptor;

import com.codefish.codefishseckill.utils.PageUtils;
import com.codefish.codefishseckill.utils.model.PageInfo;
import com.codefish.codefishseckill.utils.threadlocal.PageInfoThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/02 上午 10:51
 */
@Slf4j
public class ThreadLocalPageInfoFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //构建pageInfo
        String pageId = request.getParameter("pageId");
        String rowCount = request.getParameter("rowCount");


        PageInfo pageInfo = new PageInfo();
        if (!StringUtils.isEmpty(pageId)) {
            pageInfo.setPageId(Integer.parseInt(pageId));
        }
        if (!StringUtils.isEmpty(rowCount)) {
            pageInfo.setRowCount(Integer.parseInt(rowCount));
        }

        log.debug("请求{}是列表查询请求，获得参数：pageId={},rowCount={}", request.getRequestURI(), pageInfo.getPageId(), pageInfo.getRowCount());
        //计算数据库记录起始下标
        PageUtils.countFromIndex(pageInfo);
        //ThreadLocal设置
        PageInfoThreadLocal.set(pageInfo);
        //放行
        filterChain.doFilter(request, response);

        //计算总页数
        PageUtils.countPageSize(pageInfo);

        log.debug("请求{}的pageInfo结果为：{}", request.getRequestURI(), pageInfo);
        //ThreadLocal移除
        PageInfoThreadLocal.remove();

    }
}
